package com.lishu.carsafe.activity;

import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.Typeface;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.CombinedChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.BubbleData;
import com.github.mikephil.charting.data.BubbleDataSet;
import com.github.mikephil.charting.data.BubbleEntry;
import com.github.mikephil.charting.data.CandleData;
import com.github.mikephil.charting.data.CandleDataSet;
import com.github.mikephil.charting.data.CandleEntry;
import com.github.mikephil.charting.data.CombinedData;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.data.ScatterData;
import com.github.mikephil.charting.data.ScatterDataSet;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.lishu.carsafe.R;
import com.lishu.carsafe.model.entity.Alarm;
import com.lishu.carsafe.model.entity.AlarmStatistic;

import java.util.ArrayList;
import java.util.List;

import lecho.lib.hellocharts.listener.ComboLineColumnChartOnValueSelectListener;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Column;
import lecho.lib.hellocharts.model.ColumnChartData;
import lecho.lib.hellocharts.model.ComboLineColumnChartData;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.SubcolumnValue;
import lecho.lib.hellocharts.util.ChartUtils;
import lecho.lib.hellocharts.view.ComboLineColumnChartView;

public class StatisticsChartActivity extends StatisticsBaseActivity{
    //按月显示-饼状图
    protected PieChart alarm_chart;
    private final int ANIMATE_TIME = 1000;//动画时间//1秒钟
    //按年显示-柱状图
    /*========== 控件相关 ==========*/
    private ComboLineColumnChartView mMileDurationComboView;        //线性与柱状控件
    private ComboLineColumnChartView mPowerChargeComboView;
    private ComboLineColumnChartView mScheduleTaskComboView;
    /*========== 状态相关 ==========*/
    private boolean isHasAxes = true;                   //是否有坐标轴
    private boolean isHasAxesName = true;               //坐标轴是否有名称
    private boolean isHasPoints = true;                 //是否有节点
    private boolean isHasLines = true;                  //是否有线
    private boolean isCubic = false;                    //是否是曲线
    private boolean isHasLabels = false;                //是否有标签
    /*========== 数据相关 ==========*/
    //private int numberOfLines = 1;                      //初始线条数
    //private int maxNumberOfLines = 3;                   //最大线数
    private int numberOfPoints = 12;                    //最大点数
    //线与点的数据数组
    protected float[] mMileList = new float[numberOfPoints];
    protected float[] mDurationList = new float[numberOfPoints];
    protected float[] mPowerList = new float[numberOfPoints];
    protected float[] mChargeCountList = new float[numberOfPoints];
    protected float[] mScheduleList = new float[numberOfPoints];
    protected float[] mTaskList = new float[numberOfPoints];

    private final int COLOR_Mile = Color.parseColor("#00ADB5");
    private final int COLOR_DURATION = Color.parseColor("#FF9C5A");
    private final int COLOR_POWER = Color.parseColor("#FF9C5A");
    private final int COLOR_CHARGE = Color.parseColor("#00D0DA");
    private final int COLOR_SCHEDULE = Color.parseColor("#7C64FF");
    private final int COLOR_TASK = Color.parseColor("#00F2FE");
    private float clickPointX, clickPointY;

    @Override
    protected void initView() {
        super.initView();

        //按月显示-饼状图
        alarm_chart = findViewById(R.id.alarm_chart);
        setPieData(alarm_chart, null);
        //按年显示-柱状图
        mMileDurationComboView = findViewById(R.id.mile_duration_bar_chart);
        mPowerChargeComboView = findViewById(R.id.power_charge_bar_chart);
        mScheduleTaskComboView = findViewById(R.id.schedule_task_bar_chart);
        mMileDurationComboView.setOnTouchListener(new MyOnTouchListener());
        mPowerChargeComboView.setOnTouchListener(new MyOnTouchListener());
        mScheduleTaskComboView.setOnTouchListener(new MyOnTouchListener());
        mMileDurationComboView.setOnValueTouchListener(new MileDurationTouchListener());
        mPowerChargeComboView.setOnValueTouchListener(new PowerChargeTouchListener());
        mScheduleTaskComboView.setOnValueTouchListener(new ScheduleTaskTouchListener());
        initLineBar();
    }

    private void initLineBar() {
        for (int j = 0; j < numberOfPoints; ++j) {
            mMileList[j] = 0;
            mDurationList[j] = 0;
            mPowerList[j] = 0;
            mChargeCountList[j] = 0;
            mScheduleList[j] = 0;
            mTaskList[j] = 0;
        }
        showLineBarData();
    }

    /**
     * 每条柱状图上对应的数据
     */
    protected void setLineBarData(List<String> valueList, float[] mList) {
        for (int j = 0; j < numberOfPoints; ++j) {
            if(valueList.size() >= j){
                mList[j] = Float.valueOf(valueList.get(j));
            }else{
                mList[j] = 0;
            }
        }
    }

    protected void showLineBarData() {
        setComboDatas(mDurationList, mMileList, mMileDurationComboView, COLOR_DURATION, COLOR_Mile);            //设置所有的数据
        setComboDatas(mChargeCountList, mPowerList, mPowerChargeComboView, COLOR_CHARGE, COLOR_POWER);
        setComboDatas(mTaskList, mScheduleList, mScheduleTaskComboView, COLOR_TASK, COLOR_SCHEDULE);
    }

    private void showToast(int layout, String lineValue, String barValue) {
        View view = LayoutInflater.from(mContext).inflate(layout,null);
        TextView lineTV = (TextView) view.findViewById(R.id.line_value);
        lineTV.setText(lineValue);    //要提示的文本
        TextView barTV = (TextView) view.findViewById(R.id.bar_value);
        barTV.setText(barValue);

        Toast toast = new Toast(mContext);
        toast.setView(view);
        //toast.setGravity(Gravity.START | Gravity.TOP,0,0);
        toast.setGravity(Gravity.START | Gravity.TOP, (int)clickPointX + 20, + (int)clickPointY - 80);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.show();
    }

    private void showMileDurationToastAtIndex(int index){
        String lineDate = mDurationList[index] + getResources().getString(R.string.unit_duration);
        String barData = mMileList[index] + getResources().getString(R.string.unit_mile);
        showToast(R.layout.toast_mile_duration_layout, lineDate, barData);
    }
    private void showPowerChargeToastAtIndex(int index){
        String lineDate = (int)mChargeCountList[index] + getResources().getString(R.string.unit_charge);
        String barData = mPowerList[index] + getResources().getString(R.string.unit_power);
        showToast(R.layout.toast_power_charge_layout, lineDate, barData);
    }
    private void showScheduleTaskToastAtIndex(int index){
        String lineDate = (int)mTaskList[index] + getResources().getString(R.string.unit_task);
        String barData = mScheduleList[index] + getResources().getString(R.string.unit_schedule);
        showToast(R.layout.toast_schedult_task_layout, lineDate, barData);
    }

    /**
     * 图表点击事件
     */
    private class MileDurationTouchListener implements ComboLineColumnChartOnValueSelectListener {
        @Override
        public void onColumnValueSelected(int columnIndex, int subcolumnIndex, SubcolumnValue value) {
            showMileDurationToastAtIndex(columnIndex);
        }
        @Override
        public void onPointValueSelected(int lineIndex, int pointIndex, PointValue value) {
            showMileDurationToastAtIndex(pointIndex);
        }
        @Override
        public void onValueDeselected() {
        }
    }

    private class PowerChargeTouchListener implements ComboLineColumnChartOnValueSelectListener {
        @Override
        public void onColumnValueSelected(int columnIndex, int subcolumnIndex, SubcolumnValue value) {
            showPowerChargeToastAtIndex(columnIndex);
        }
        @Override
        public void onPointValueSelected(int lineIndex, int pointIndex, PointValue value) {
            showPowerChargeToastAtIndex(pointIndex);
        }
        @Override
        public void onValueDeselected() {
        }
    }

    private class ScheduleTaskTouchListener implements ComboLineColumnChartOnValueSelectListener {
        @Override
        public void onColumnValueSelected(int columnIndex, int subcolumnIndex, SubcolumnValue value) {
            showScheduleTaskToastAtIndex(columnIndex);
        }
        @Override
        public void onPointValueSelected(int lineIndex, int pointIndex, PointValue value) {
            showScheduleTaskToastAtIndex(pointIndex);
        }
        @Override
        public void onValueDeselected() {
        }
    }

    /**
     * 设置结合起来的数据
     */
    private void setComboDatas(float[] lineDateList, float[] barDateList, ComboLineColumnChartView comboView,
                               int lineColor, int barColor) {
        //需要同时设置柱状数据和线性数据
        ComboLineColumnChartData comboData = new ComboLineColumnChartData(setColumnData(barDateList, barColor), setLineData(lineDateList, lineColor));
        //坐标轴的相关设置 类似 Line Chart
        if (isHasAxes) {
            Axis axisX = new Axis();
            List<AxisValue> axisValues = new ArrayList<>();
            for(int i = 0 ; i <12 ; i++){
                AxisValue axisValue = new AxisValue(i);
                //axisValue.setValue(i);
                axisValue.setLabel(i+1 + "月");
                axisValues.add(axisValue);
            }
            axisX.setValues(axisValues);
            axisX.setTextSize(9);

            Axis axisY = new Axis().setHasLines(true);
            axisY.setHasLines(false);
            axisY.setTextSize(9);

            comboData.setAxisXBottom(axisX);
            comboData.setAxisYLeft(axisY);
        } else {
            comboData.setAxisXBottom(null);
            comboData.setAxisYLeft(null);
        }
        //设置数据
        comboView.setZoomEnabled(false);
        comboView.setComboLineColumnChartData(comboData);
    }

    /**
     * 设置线性图数据
     */
    private LineChartData setLineData(float[] dateList, int lineColor) {
        List<Line> lines = new ArrayList<>();

        //for (int i = 0; i < numberOfLines; ++i) {
            List<PointValue> values = new ArrayList<>();
            for (int j = 0; j < numberOfPoints; ++j) {
                values.add(new PointValue(j, dateList[j]));
            }

            Line line = new Line(values);
            line.setColor(lineColor);
            line.setCubic(isCubic);
            line.setHasLabels(isHasLabels);
            line.setHasLines(isHasLines);
            line.setHasPoints(isHasPoints);
            lines.add(line);

        //}
        return new LineChartData(lines);
    }

    /**
     * 设置柱状图数据
     */
    private ColumnChartData setColumnData(float[] dateList, int barColor) {
        //int numSubcolumns = 1;
        int numColumns = 12;

        List<Column> columns = new ArrayList<>();
        List<SubcolumnValue> values;

        for (int i = 0; i < numColumns; ++i) {
            values = new ArrayList<>();
            //for (int j = 0; j < numSubcolumns; ++j) {
                values.add(new SubcolumnValue(dateList[i], barColor));
            //}
            columns.add(new Column(values));
        }

        return new ColumnChartData(columns);
    }

    /**
     * 饼图
     */
    private void initPieChart(PieChart chart){
        //Legend显示位置
        Legend l = chart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        //l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setTextSize(11f);
        //去掉描述文字
        chart.getDescription().setEnabled(false);
        //去掉图中label
        chart.setDrawEntryLabels(false);

        chart.animateY(ANIMATE_TIME, Easing.EaseInOutQuad);
    }

    /**
     * 饼图
     */
    protected void setPieData(PieChart chart, AlarmStatistic alarmInfo) {
        if(alarmInfo == null){
            chart.clear();
            chart.setNoDataText("暂无数据");
            return;
        }

        List<Alarm> alarms = alarmInfo.getAlarms();
        int sumCount = alarmInfo.getSumCount();
        alarm_total.setText("总告警次数：" + sumCount + "次");

        if(sumCount < 1) {
            chart.clear();
            chart.setNoDataText("暂无数据");
            return;
        }
        initPieChart(chart);

        float total = (float) sumCount / 100L;
        List<PieEntry> entries = new ArrayList<>();
        ArrayList<Integer> colors = new ArrayList<>();
        for(int i = 0; i < alarms.size(); i++){
            entries.add(new PieEntry((float)(alarms.get(i).getCount()) / total, alarms.get(i).getName()));
        }

        colors.add(getResources().getColor(R.color.statistics_blue));
        colors.add(getResources().getColor(R.color.statistics_yellow));
        colors.add(getResources().getColor(R.color.statistics_red));
        colors.add(getResources().getColor(R.color.tab_normal_bgd));
        colors.add(getResources().getColor(R.color.main_color));
        colors.add(getResources().getColor(R.color.split_line));
        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);

        PieDataSet dataSet = new PieDataSet(entries, "");
        dataSet.setColors(colors);
        PieData pieData = new PieData(dataSet);
        //显示百分比
        //pieData.setDrawValues(true);
        chart.setUsePercentValues(true);
        pieData.setValueFormatter(new PercentFormatter(chart));
        //字体大小
        pieData.setValueTextSize(11f);
        pieData.setValueTextColor(Color.BLACK);

        //设置数据
        chart.setData(pieData);
        chart.invalidate();
    }

    //OnTouch监听器
    private class MyOnTouchListener implements View.OnTouchListener {
        @Override
        public boolean onTouch(View v, MotionEvent event){
            clickPointX = event.getRawX();
            clickPointY = event.getRawY();
            return false;
        }
    }
}
